<?php
/**
 * http://blog.sina.com.cn/s/blog_6ca907a60100m37o.html
 * this class depends php_mcrypt.dll
 * in windows, you should put libmcrypt.dll to system directory
 *
 * @author tom.wang<tom.wang.sz@qq.com>
 */
class DesUtil
{
    private static $key;
    private static $iv;

	/**
	 * set config
	 *
	 * @param string $key
	 * @param int $iv
	 */
    public static function setCfg( $key, $iv=0) {
        self::$key = $key;
        if( $iv == 0 ) {
            self::$iv = $key;
        } else {
            self::$iv = $iv;
        }
    }
	
	/**
	 * encrypt data
	 *
	 * @param string $str
	 */
    public static function encrypt($str) {
        $size = mcrypt_get_block_size(MCRYPT_DES,MCRYPT_MODE_CBC);
        $str = self::pkcs5Pad ( $str, $size );
        return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, self::$key, $str, MCRYPT_ENCRYPT, self::$iv ) ) );
    }

	/**
	 * decrypt data
	 *
	 * @param string $str
	 */
    public static function decrypt($str) {
        $strBin = self::hex2bin( strtolower( $str ) );
        $str = mcrypt_cbc( MCRYPT_DES, self::$key, $strBin, MCRYPT_DECRYPT, self::$iv );
        $str = self::pkcs5Unpad( $str );
        return $str;
    }

    private static function hex2bin($hexData) {
        $binData = "";
        for($i = 0; $i < strlen ( $hexData ); $i += 2) {
            $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
        }
        return $binData;
    }

    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }

    private static function pkcs5Unpad($text) {
        $pad = ord ( $text {strlen ( $text ) - 1} );
        if ($pad > strlen ( $text ))
            return false;
        if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
            return false;
        return substr ( $text, 0, - 1 * $pad );
    }

}
?>